const db = uniCloud.database();
const dbDutyPeople = db.collection("duty-people");

module.exports = {
	async getAllDutyPeople() {
		try {
			const res = await dbDutyPeople.where({
				selected: true
			}).get();
			return {
				code: 0,
				data: res.data
			};
		} catch (e) {
			return {
				code: -1,
				msg: '获取失败',
				error: e
			};
		}
	},

	async saveDutyPeople(event) {
		const dutyList = event.data || [];
		if (!Array.isArray(dutyList)) {
			return {
				code: 1,
				message: "参数错误"
			};
		}

		try {
			// 1. 获取所有当前记录
			const allRecords = await dbDutyPeople.get();
			// 2. 构建所有要更新或插入的数据
			const updatePromises = [];
			const insertPromises = [];
			const selectedIds = new Set(dutyList.map(item => item.userId));
			// 先处理已存在的记录：未选中的设为 selected: false
			allRecords.data.forEach(record => {
				const isSelected = selectedIds.has(record.userId);
				updatePromises.push(
					dbDutyPeople.doc(record._id).update({
						selected: isSelected
					})
				);
			});
			// 再处理新选中的记录（如果不存在就插入）
			dutyList.forEach(item => {
				if (!allRecords.data.some(r => r.userId === item.userId)) {
					insertPromises.push(
						dbDutyPeople.add({
							...item,
							selected: true,
							createTime: new Date()
						})
					);
				}
			});
			// 执行所有更新和插入
			await Promise.all([...updatePromises, ...insertPromises]);
			return {
				code: 0,
				message: "保存成功"
			};
		} catch (err) {
			console.error("保存失败:", err);
			return {
				code: 1,
				message: "保存失败"
			};
		}
	},

	async getDutyPeople() {
		try {
			// ✅ 查询所有记录（不要加 selected: false）
			const res = await dbDutyPeople.where({
				"selected": true
			}).get();

			return {
				code: 0,
				message: '获取成功',
				data: res.data || [] // 确保 data 是数组
			};
		} catch (e) {
			console.error('获取值班数据失败:', e); // 加个日志
			return {
				code: -1,
				message: '获取失败'
			};
		}
	},

	async saveChangedDutyPeople(event) {
		const db = uniCloud.database();
		const collection = db.collection('duty-people');
		const {
			data
		} = event;
		for (const entry of data) {
			const {
				date,
				leaders,
				staffs
			} = entry;
			// 处理带班领导
			for (const leader of leaders) {
				const existing = await collection.where({
					date,
					id: leader.id,
					type: 'leaders'
				}).get();
				if (existing.data.length > 0) {
					await collection.doc(existing.data[0]._id).update(leader);
				} else {
					await collection.add({
						date,
						id: leader.id,
						name: leader.name,
						type: 'leaders',
						selected: leader.selected
					});
				}
			}
			// 处理值班职工
			for (const staff of staffs) {
				const existing = await collection.where({
					date,
					id: staff.id,
					type: 'staffs'
				}).get();
				if (existing.data.length > 0) {
					await collection.doc(existing.data[0]._id).update(staff);
				} else {
					await collection.add({
						date,
						id: staff.id,
						name: staff.name,
						type: 'staffs',
						selected: staff.selected
					});
				}
			}
		}
		return {
			code: 0,
			message: '部分数据已更新'
		};
	},
	
	_before: function() {
		// 可以在这里做权限验证、登录校验等通用预处理
	},
};